function trim(stringToTrim){
    return stringToTrim.replace(/^\s+|\s+$/g, "");
}

function externalLinks(){
    var linkArray = document.getElementsByTagName('a');
    for (var i = 0; i < linkArray.length; i++) {
        var link = linkArray[i];
        if (link.getAttribute('rel') == 'external') {
            link.target = '_blank';
        }
    }
}

function isLogin(){
    if (g_is_login == "true") 
        return true;
    else 
        return false;
}

function doLoginJS(){
    g_is_login = "true";
}

function doLogoutJS(){
    g_is_login = "false";
}

/**
 * display a message box
 */
function showMessage(msg){
    var divMsg = document.getElementById("div_message_text");
    
    divMsg.innerHTML = msg;
    YAHOO.org.charry.dialog_msgbox.show();
}

/**
 * init message box control
 */
function initMessageBox(){
    // Define various event handlers for Dialog
    var handleSubmit = function(){
        YAHOO.org.charry.dialog_msgbox.hide();
    };
    
    // Instantiate the Dialog 
    YAHOO.org.charry.dialog_msgbox = new YAHOO.widget.Dialog("div_message_box", {
        width: "25em",
        fixedcenter: true,
        modal: true,
        zIndex: 10000,
        visible: false,
        constraintoviewport: true,
        buttons: [{
            text: "Ok",
            handler: handleSubmit,
            isDefault: true
        }]
    });
    
    // Render the Dialog 
    YAHOO.org.charry.dialog_msgbox.render();
}

/**
 * init dialog for project editor
 */
function initDialogEdit(){
    if (YAHOO.org.charry.dialog_edit != null) 
        return;
    
    document.getElementById("div_dialog_edit").style.display = "block";
    
    // Define various event handlers for Dialog
    var handleSubmit = function(){
        this.submit();
    };
    
    var handleCancel = function(){
        this.cancel();
    };
    
    var handleSuccess = function(o){
        var response = o.responseText;
        response = response.split("<!")[0];
        window.location.reload(true);
    };
    
    var handleFailure = function(o){
        alert("Submission failed: " + o.status);
    };
    
    // Instantiate the Dialog 
    YAHOO.org.charry.dialog_edit = new YAHOO.widget.Dialog("div_dialog_edit", {
        width: "35em",
        fixedcenter: true,
        zIndex: 10000,
        visible: false,
        constraintoviewport: true,
        buttons: [{
            text: "Submit",
            handler: handleSubmit,
            isDefault: true
        }, {
            text: "Cancel",
            handler: handleCancel
        }]
    });
    
    // Validate the entries in the form
    YAHOO.org.charry.dialog_edit.validate = function(){
        var data = this.getData();
        
        if (data.prj_title == "") {
            showMessage("Please enter project title.");
            return false;
        }
        
        if (data.start_time == "") {
            showMessage("Please enter start time");
            return false;
        }
        
        return true;
    };
    
    // Wire up the success and failure handlers 
    YAHOO.org.charry.dialog_edit.callback = {
        success: handleSuccess,
        failure: handleFailure
    };
    
    // Render the Dialog 
    YAHOO.org.charry.dialog_edit.render();
    
    initCalendar();
    initColorPicker();
    initSlideButton();
}

/**
 * init dialog for login
 */
function initDialogLogin(){
    // lazy loading
    if (YAHOO.org.charry.dialog_login != null) 
        return;
    
    initLoginStatusPanel();
    
    var handleSubmit = function(){
        YAHOO.org.charry.loginStatus.show();
        this.submit();
    };
    
    var handleCancel = function(){
        this.cancel();
    };
    
    var handleSuccess = function(o){
        var response = o.responseText;
        response = response.split("<!")[0];
        
        YAHOO.org.charry.loginStatus.hide();
        // login successfully
        if (trim(response) == "true") {
            doLoginJS();
            adjustPanelProperty();
        }
        else {
            showMessage('failed to login, please double check your username or password')
        }
    };
    
    var handleFailure = function(o){
        alert("Submission failed: " + o.status);
    };
    
    YAHOO.org.charry.dialog_login = new YAHOO.widget.Dialog("dialog_login", {
        width: "24em",
        modal: true,
        fixedcenter: true,
        zIndex: 30001,
        visible: false,
        constraintoviewport: true,
        buttons: [{
            text: "Submit",
            handler: handleSubmit,
            isDefault: true
        }, {
            text: "Cancel",
            handler: handleCancel
        }]
    });
    
    // Wire up the success and failure handlers 
    YAHOO.org.charry.dialog_login.callback = {
        success: handleSuccess,
        failure: handleFailure
    };
    
    YAHOO.org.charry.dialog_login.render();
}

function initLoginStatusPanel(){
    YAHOO.org.charry.loginStatus = new YAHOO.widget.Overlay("loginStatus", {
        // xy: [600, 200],
        visible: false,
        fixedcenter: true,
        zIndex: 30000,
        width: "300px"
    });
    
    YAHOO.org.charry.loginStatus.render();
}

function init(){
    initMessageBox();
}

function getProjectInfo(pid){
    if (isLogin() == false) {
        showMessage("You're not logged in");
        return;
    }
    
    var id = document.getElementById("id");
    var owner = document.getElementById("owner");
    var prj_title = document.getElementById("prj_title");
    var start_time = document.getElementById("start_time");
    var end_time = document.getElementById("end_time");
    var image = document.getElementById("image");
    var icon = document.getElementById("icon");
    var color = document.getElementById("color");
    var tape_image = document.getElementById("tape_image");
    var page_url = document.getElementById("page_url");
    var title_link = document.getElementById("title_link");
    var priority = document.getElementById("priority");
    var complete = document.getElementById("complete");
    var prj_id = document.getElementById("prj_id");
    var is_duration = document.getElementById("is_duration");
    var description = document.getElementById("description");
    
    var loading_span = document.getElementById("loading_flag");
    loading_span.innerHTML = " - <img src='images/loading.gif' align='absmiddle' title='loading...' />Loading...";
    
    $.ajax({
        'url': 'project_info.php',
        'data': "pid=" + pid,
        'type': 'POST',
        'success': function(data){
            eval('myjson=' + data + ';');
            id.value = myjson.ID;
            owner.value = myjson.OWNER;
            prj_title.value = myjson.TITLE;
            start_time.value = myjson.START_TIME;
            description.value = myjson.DESCRIPTION;
            end_time.value = myjson.END_TIME;
            image.value = myjson.IMAGE;
            color.value = myjson.COLOR;
            icon.value = myjson.ICON;
            tape_image.value = myjson.TAPE_IMAGE;
            page_url.value = myjson.PAGE_URL;
            priority.options[myjson.PRIORITY].selected = true;
            prj_id.value = myjson.PRJ_ID;
            
            // duration
            if (is_duration.options[0].value == myjson.IS_DURATION) 
                is_duration.options[0].selected = true;
            else 
                is_duration.options[1].selected = true;
            
            complete.value = myjson.COMPLETE;
            
            loading_span.innerHTML = "";
        },
        'error': function(){
            alert('error');
        }
    });
    
    initDialogEdit();
    YAHOO.org.charry.dialog_edit.show();
}

function delProject(prj_id){
    if (isLogin() == false) {
        showMessage("You're not logged in.");
        return;
    }
    
    $.ajax({
        'url': 'global_functions.php',
        'data': "action=del&pid=" + prj_id,
        'type': 'POST',
        'success': function(data){
            window.location.reload(true);
        },
        'error': function(data){
            alert('error');
        }
    });
}

// add a new entry, the time will be set as current time
function createProject(){
    if (confirm('Are you sure you want to add an untitled project entry?') == false) 
        return;
    
    $.ajax({
        'url': 'global_functions.php',
        'type': 'POST',
        'data': "action=add",
        'success': function(data){
            window.location.reload(true);
        },
        'error': function(){
            alert('error');
        }
    });
}

function adjustUI(){
    adjustPanelPosition();
    adjustPanelProperty();
}

function adjustPanelPosition(){
    // document.getElementById("dashboard").style.top = document.getElementById("my-timeline").offsetTop + 1;
    document.getElementById("dashboard").style.left = document.getElementById("my-timeline").offsetLeft;
}

function adjustPanelProperty(){
    // show/hide login/admin panel
    var loginPanel = document.getElementById("login_panel");
    var dashboard = document.getElementById("dashboard");
    
    if (isLogin() == true) {
        loginPanel.style.display = "block";
        dashboard.style.display = "block";
        loginPanel.innerHTML = "<a href='#' onclick='doLogoutPHP();'>Logout</a>";
    }
}

function showDialogLogin(){
    initDialogLogin();
    
    document.getElementById("dialog_login").style.display = "block";
    YAHOO.org.charry.dialog_login.show();
}

function doLogoutPHP(){
    document.getElementById("dashboard").style.display = "none";
    
    var loginPanel = document.getElementById("login_panel");
    loginPanel.innerHTML = "<a href='#' onclick='showDialogLogin();'>Login</a>";
    $.ajax({
        'url': 'global_functions.php',
        'type': 'POST',
        'data': "action=logout",
        'success': function(data){
            // NOOP
        },
        'error': function(){
            alert('error');
        }
    });
    
    doLogoutJS();
}

function initCalendar(){
    // lazy loading
    if (calendar != null) 
        return;
    
    var dialog, calendar, dialog2, calendar2;
    
    // Calendar 1
    calendar = new YAHOO.widget.Calendar("show_start", "cal", {
        iframe: false, // Turn iframe off, since container has iframe support.
        hide_blank_weeks: true // Enable, to demonstrate how we handle changing height, using changeContent
    });
    
    function cancelHandler(){
        this.hide();
    }
    
    function okHandler(){
        if (calendar.getSelectedDates().length > 0) {
            var selDate = calendar.getSelectedDates()[0];
            
            var dStr = selDate.getDate();
            if (dStr < 10) {
                dStr = "0" + dStr;
            }
            
            var mStr = selDate.getMonth() + 1;
            if (mStr < 10) {
                mStr = "0" + mStr;
            }
            var yStr = selDate.getFullYear();
            var fulldate = yStr + "-" + mStr + "-" + dStr + " 08:00:00";
            document.getElementById("start_time").value = fulldate;
        }
        else {
            // NOOP
        }
        
        this.hide();
    }
    dialog = new YAHOO.widget.Dialog("cal_container", {
        context: ["show_start", "tl", "bl"],
        buttons: [{
            text: "Select",
            isDefault: true,
            handler: okHandler
        }, {
            text: "Cancel",
            handler: cancelHandler
        }],
        width: "16em", // Sam Skin dialog needs to have a width defined (7*2em + 2*1em = 16em).
        draggable: false,
        close: true
    });
    
    calendar.render();
    dialog.render();
    
    YAHOO.util.Event.on("show_start", "click", dialog.show, dialog, true);
    
    calendar.selectEvent.subscribe(function(){
        dialog.hide();
        okHandler();
        calendar.reset();
    });
    
    dialog.hide();
    
    // Calendar 2
    function cancelHandler2(){
        this.hide();
    }
    
    function okHandler2(){
        if (calendar2.getSelectedDates().length > 0) {
            var selDate = calendar2.getSelectedDates()[0];
            
            var dStr = selDate.getDate();
            if (dStr < 10) {
                dStr = "0" + dStr;
            }
            
            var mStr = selDate.getMonth() + 1;
            if (mStr < 10) {
                mStr = "0" + mStr;
            }
            var yStr = selDate.getFullYear();
            var fulldate = yStr + "-" + mStr + "-" + dStr + " 17:00:00";
            document.getElementById("end_time").value = fulldate;
        }
        else {
            // NOOP
        }
        
        this.hide();
    }
    
    calendar2 = new YAHOO.widget.Calendar("show_end", "cal2", {
        iframe: false, // Turn iframe off, since container has iframe support.
        hide_blank_weeks: true // Enable, to demonstrate how we handle changing height, using changeContent
    });
    
    dialog2 = new YAHOO.widget.Dialog("cal_container2", {
        context: ["show_end", "tl", "bl"],
        buttons: [{
            text: "Select",
            isDefault: true,
            handler: okHandler2
        }, {
            text: "Cancel",
            handler: cancelHandler2
        }],
        width: "16em", // Sam Skin dialog needs to have a width defined (7*2em + 2*1em = 16em).
        draggable: false,
        close: true
    });
    
    calendar2.render();
    dialog2.render();
    
    YAHOO.util.Event.on("show_end", "click", dialog2.show, dialog2, true);
    
    calendar2.selectEvent.subscribe(function(){
        dialog2.hide();
        okHandler2();
        calendar2.reset();
    });
    
    dialog2.hide();
}

// create a color picker for edit dialog
function initColorPicker(){
    // lazy loading
    if (dlg_color_picker != null) 
        return;
    
    document.getElementById("yui-picker-panel").style.display = "block";
    
    function handlerSubmit(){
        document.getElementById("color").value = "#" + document.getElementById("yui-picker-hex").value
        dlg_color_picker.hide();
    }
    
    function handlerCancel(){
        dlg_color_picker.hide();
    }
    
    var dlg_color_picker = new YAHOO.widget.Dialog("yui-picker-panel", {
        width: "500px",
        height: "295px",
        close: true,
        fixedcenter: true,
        visible: false,
        zIndex: 30000,
        constraintoviewport: true,
        buttons: [{
            text: "Ok",
            isDefault: true,
            handler: handlerSubmit
        }, {
            text: "Cancel",
            handler: handlerCancel
        }]
    });
    
    dlg_color_picker.validate = function(){
        return true;
    };
    
    picker = new YAHOO.widget.ColorPicker("yui-picker", {
        images: {
            PICKER_THUMB: "libs/yui/colorpicker/assets/picker_thumb.png",
            HUE_THUMB: "libs/yui/colorpicker/assets/hue_thumb.png"
        }
    });
    
    dlg_color_picker.render();
    
    YAHOO.util.Event.on("show_color_picker", "click", dlg_color_picker.show, dlg_color_picker, true);
}

function initSlideButton(){
    var Dom = YAHOO.util.Dom, oSlider;
    
    var oSpan = document.createElement("span")
    
    Dom.get("div_complete").appendChild(oSpan);
    
    /*
     Create a Menu instance whose body element will house a
     Slider instance.
     */
    var oSlideCompleteMenu = new YAHOO.widget.Menu("complete_menu", {
        width: "240px"
    });
    
    /*
     Create a new Button instance, wrapping the label in an
     <em> element.  The <em> element will be used to give the
     Button instance a fixed width to prevent it from growing
     and shrinking as the text label is updated.
     */
    var oButton = new YAHOO.widget.Button({
        type: "menu",
        id: "btn_complete",
        label: "Slider",
        menu: oSlideCompleteMenu,
        container: oSpan
    });
    
    oButton.on("appendTo", function(){
        // Add Slider markup to the Menu instance's body element
        oSlideCompleteMenu.setBody("<div id=\"slider-bg\" tabindex=\"1\" title=\"Slider\"><div id=\"slider-thumb\"><img src=\"libs/yui/assets/thumb-n.gif\"></div></div>");
        
        /*
         Render the Menu instance into the element specified as the
         Button instance's container
         */
        oSlideCompleteMenu.render(this.get("container"));
    });
    
    /*
     Add a "beforeShow" event handler to the Menu instance that
     will instantiate the Slider.
     */
    var onMenuBeforeShow = function(){
        // Instantiate the Slider
        oSlider = YAHOO.widget.Slider.getHorizSlider("slider-bg", "slider-thumb", 0, 200, 1);
        
        // Maintain a reference to the Slider instance's root element
        var oSliderEl = Dom.get("slider-bg");
        
        // Subscribe to the Slider instance's "change" event
        oSlider.subscribe("change", function(){
            var nValue = (Math.round(oSlider.getValue() * .5)), nOpacity = (nValue * .01);
            document.getElementById("complete").value = nValue;
        });
        
        var focusSlider = function(){
            if ((YAHOO.env.ua.ie || YAHOO.env.ua.gecko) && oSliderEl) {
                window.setTimeout(function(){
                    oSliderEl.focus();
                }, 0);
            }
        };
        
        focusSlider();
        
        // Focus the Slider instance each time it is made visible
        oSlideCompleteMenu.subscribe("show", focusSlider);
        
        // Unsubscribe from the "beforeShow" event, since we only need to initialize the 
        // Slider once.
        
        oSlideCompleteMenu.unsubscribe("beforeShow", onMenuBeforeShow);
    };
    
    oSlideCompleteMenu.subscribe("beforeShow", onMenuBeforeShow);
}

function initDialogCategory(){
    // lazy loading
    if (YAHOO.org.charry.dialog_category != null) 
        return;
    
    // Define various event handlers for Dialog
    var handleClose = function(){
        // window.location.reload(true);
        
        YAHOO.org.charry.dialog_category.hide();
    };
    
    var handleNew = function(){
        initDialogCategoryEdit();
        showDialogCategoryEditor("-1", "", "", "", "", "");
    };
    
    var handleSuccess = function(o){
        var response = o.responseText;
        response = response.split("<!")[0];
        window.location.reload(true);
    };
    
    var handleFailure = function(o){
        alert("Submission failed: " + o.status);
    };
    
    // Instantiate the Dialog 
    var dialog_width = 600;
    YAHOO.org.charry.dialog_category = new YAHOO.widget.Dialog("div_dialog_category", {
        width: dialog_width,
        // fixedcenter: true,
        x: screen.width / 2 - dialog_width / 2,
        y: 100,
        zIndex: 10000,
        visible: false,
        constraintoviewport: true,
        buttons: [{
            text: "New",
            handler: handleNew
        }, {
            text: "Close",
            handler: handleClose,
            isDefault: true
        }]
    });
    
    // Wire up the success and failure handlers 
    YAHOO.org.charry.dialog_category.callback = {
        success: handleSuccess,
        failure: handleFailure
    };
    
    // Render the Dialog 
    YAHOO.org.charry.dialog_category.render();
}

function initDialogCategoryEdit(){
    // lazy-loading
    if (YAHOO.org.charry.dialog_category_edit != null) 
        return;
    
    document.getElementById("div_dialog_category_edit").style.display = "block";
    
    // Define various event handlers for Dialog
    var handleUpdateOrAdd = function(){
        document.getElementById("category_action").value = "update_or_add";
        this.submit();
    };
    
    var handleDelete = function(){
        document.getElementById("category_action").value = "delete";
        this.submit();
    };
    
    var handleCancel = function(){
        this.cancel();
    };
    
    var handleSuccess = function(o){
        var response = o.responseText;
        response = response.split("<!")[0];
        window.location.reload(true);
    };
    
    var handleFailure = function(o){
        alert("Submission failed: " + o.status);
    };
    
    // Instantiate the Dialog 
    YAHOO.org.charry.dialog_category_edit = new YAHOO.widget.Dialog("div_dialog_category_edit", {
        width: "35em",
        fixedcenter: true,
        zIndex: 10000,
        visible: false,
        constraintoviewport: true,
        buttons: [{
            text: "Update/Add",
            handler: handleUpdateOrAdd,
            isDefault: true
        }, {
            text: "Delete",
            handler: handleDelete
        }, {
            text: "Cancel",
            handler: handleCancel
        }]
    });
    
    // Validate the entries in the form
    YAHOO.org.charry.dialog_category_edit.validate = function(){
        var data = this.getData();
        
        return true;
    };
    
    // Wire up the success and failure handlers 
    YAHOO.org.charry.dialog_category_edit.callback = {
        success: handleSuccess,
        failure: handleFailure
    };
    
    // Render the Dialog 
    YAHOO.org.charry.dialog_category_edit.render();
}

function reloadDatasource(){
    var myColumnDefs = [{
        key: "id",
        label: "ID",
        resizeable: true,
        // width: 200,
        sortable: true
    }, {
        key: "prj_id",
        // width: 200,
        label: "Project ID",
        sortable: true
    }, {
        key: "color",
        // width: 200,
        label: "Color",
        sortable: true
    }, {
        key: "icon",
        // width: 200,
        label: "Icon",
        sortable: true
    }, {
        key: "tape_image",
        // width: 200,
        label: "Tape Image",
        sortable: true
    }, {
        key: "title_link",
        // width: 200,
        label: "Title Link",
        sortable: true
    }];
    
    var parseNumberFromCurrency = function(sString){
        // Remove dollar sign and make it a float
        return parseFloat(sString.substring(1));
    };
    
    var myConfigs = {
        // Set up initial sort state
        sortedBy: {
            key: "id",
            dir: "prj_id"
        },
        paginator: new YAHOO.widget.Paginator({
            rowsPerPage: 5
        })
    };
    
    var myDataSource = new YAHOO.util.DataSource("category_xml.php?dummy=" + new Date().getTime());
    myDataSource.responseType = YAHOO.util.DataSource.TYPE_XML;
    myDataSource.responseSchema = {
        resultNode: "item", // Name of the node for each result
        fields: [{
            key: "id"
        }, {
            key: "prj_id"
        }, {
            key: "color"
        }, {
            key: "icon"
        }, {
            key: "tape_image"
        }, {
            key: "title_link"
        }],
        metaNode: "data" // Name of the node holding meta data
    };
    
    var myDataTable = new YAHOO.widget.DataTable("prj_category", myColumnDefs, myDataSource, myConfigs);
    myDataTable.subscribe("rowClickEvent", myDataTable.onEventSelectRow);
    myDataTable.subscribe("rowMouseoverEvent", myDataTable.onEventHighlightRow);
    myDataTable.subscribe("rowMouseoutEvent", myDataTable.onEventUnhighlightRow);
    
    function foo(oArgs){
        initDialogCategoryEdit();
        
        var a = oArgs.target;
        var rec = this.getRecord(oArgs.target);
        
        // alert(rec.getData('id') + ":" + rec.getData('title_link'));
        
        var id = rec.getData('id');
        var prj_id = rec.getData('prj_id');
        var color = rec.getData('color');
        var tape_image = rec.getData('tape_image');
        var icon = rec.getData('icon');
        var title_link = rec.getData('title_link');
        showDialogCategoryEditor(id, prj_id, color, icon, tape_image, title_link);
        
        // reloadDatasource();
    }
    
    myDataTable.subscribe("rowDblclickEvent", foo);
}

function showDialogCategoryEditor(id, prj_id, color, icon, tape_image, title_link){
    var cat_inner_id = document.getElementById("cat_inner_id");
    var cat_prj_id = document.getElementById("cat_prj_id");
    var cat_color = document.getElementById("cat_color");
    var cat_tape_image = document.getElementById("cat_tape_image");
    var cat_icon = document.getElementById("cat_icon");
    var cat_title_link = document.getElementById("cat_title_link");
    
    cat_inner_id.value = id;
    cat_prj_id.value = prj_id;
    cat_color.value = color;
    cat_icon.value = icon;
    cat_tape_image.value = tape_image;
    cat_title_link.value = title_link;
    
    YAHOO.org.charry.dialog_category_edit.show();
}

function showDialogCategory(){
    initDialogCategory();
    
    document.getElementById("div_dialog_category").style.display = "block";
    reloadDatasource();
    YAHOO.org.charry.dialog_category.show();
}

YAHOO.namespace("org.charry");
YAHOO.util.Event.onDOMReady(init);
window.onresize = onResize;
